package com.dexter.year2023.charpter7_tree_and_recurison.level3;

import com.dexter.year2023.charpter6_tree_level_travel.level1.TreeNode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

/**
 * 非递归的后序遍历
 *
 * @author Dexter
 */
public class PostOrderTraversal {
    public static void main(String[] args) {
        TreeNode node = new TreeNode(3);
        node.left = new TreeNode(9);
        node.right = new TreeNode(20);
        node.right.left = new TreeNode(15);
        node.right.right = new TreeNode(7);
        System.out.println(postOrderTraversal(node));
    }

    /**
     * 反转法
     * <p>
     * 思路：{9,15,7,20,3} 整体反转后就是{3,20,7,15,9} 就是前序{3,9,20,15,7}将中左右换成了“中右左”
     *
     * @param root
     * @return
     */
    public static List<Integer> postOrderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        // 每次访问的节点入栈
        Stack<TreeNode> stack = new Stack<>();
        // 从root开始遍历
        TreeNode node = root;
        while (!stack.isEmpty() || node != null) {
            while (node != null) {
                // 中
                res.add(node.val);
                stack.push(node);
                // 右
                node = node.right;
            }
            node = stack.pop();
            // 左
            node = node.left;
        }
        Collections.reverse(res);
        return res;
    }
}
